/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nc.solutions.rentacar.domain.Money.impl;

import com.nc.solutions.rentacar.domain.Money.util.MoneyException;
import com.nc.solutions.rentacar.domain.Money.util.Currency;

/**
 *
 * @author Andrey
 */
public class Money {

	double value;
	Currency currency;

	public Money() {
		value = 0;
		currency = Currency.EUR;
	}

	public Money(double val, Currency cur) {
		if (val < 0) {
			throw new MoneyException("money value below zero");
		} else {
			value = val;
			currency = cur;
		}
	}

	public double getValue() {
		return value;
	}

	protected void setValue(double value) {
		this.value = value;
	}

	public Currency getCurrency() {
		return currency;
	}
	
	/*
	 * unsafe
	 */
	protected void setCurrency(Currency value) {
		this.currency = value;
	}

	public void convert(Currency cur) {
		double k = this.getCurrency().getConvertRate(cur);//коэффициент, который берется из базы к примеру или из енама.
		this.setValue(k * this.getValue());
		this.setCurrency(cur);
	}

	public static Money sub(Money a, Money b) {
		if (a.getCurrency().equals(b.getCurrency())) {
			return new Money(a.getValue() - b.getValue(), a.getCurrency());
		} else {
			throw new MoneyException("different currencies");
		}
	}

	public static Money summ(Money a, Money b) {
		if (a.getCurrency().equals(b.getCurrency())) {
			return new Money(a.getValue() + b.getValue(), a.getCurrency());
		} else {
			throw new MoneyException("different currencies");
		}
	}

	public static Money mult(Money a, double b) {

		return new Money(b * a.getValue(), a.getCurrency());

	}

	public static double div(Money a, Money b) {
		if (a.getCurrency().equals(b.getCurrency())) {
			return a.getValue() / b.getValue();
		} else {
			throw new MoneyException("different currencies");
		}
	}

	public static Money div(Money a, double b) {

		return new Money(a.getValue() / b, a.getCurrency());

	}
}
